import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from email.header import Header

# 1. 配置邮箱信息
smtp_server = 'smtp.163.com'  # 163邮箱SMTP服务器
smtp_port = 465               # SSL端口号
sender_email = 'ls007player@163.com'  # 你的邮箱
password = 'GFNtUBhBDZJ5wnpY'  # 授权码（非邮箱密码）
receiver_email = '1054155480@qq.com'  # 收件人邮箱

# 2. 创建复合邮件对象
msg = MIMEMultipart()
# 尝试直接使用邮箱地址作为发件人
msg['From'] = sender_email  # 直接使用邮箱地址
msg['To'] = receiver_email  # 收件人邮箱
msg['Subject'] = '【Python邮件测试】10月考勤表'  # 邮件主题

# 3. 添加邮件正文
body = """
尊敬的同事：
您好！
这是本月的考勤表，请查收附件。

祝工作顺利！
"""
text_part = MIMEText(body, 'plain', 'utf-8')  # 正文内容
msg.attach(text_part)

# 4. 添加附件（可选）
file_path = './material/10月员工绩效表.xlsx'  # 附件路径
with open(file_path, 'rb') as f:
    attachment = MIMEBase('application', 'octet-stream')
    attachment.set_payload(f.read())
    encoders.encode_base64(attachment)  # 对附件进行Base64编码
    attachment.add_header('Content-Disposition', f'attachment; filename="{file_path.split("/")[-1]}"')
    msg.attach(attachment)

# 5. 登录并发送邮件
try:
    with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, [receiver_email], msg.as_string())
    print("邮件发送成功！")
except Exception as e:
    print(f"邮件发送失败：{str(e)}")